package com.openingedu.mba.service.task.impl;

import java.util.List;

import android.content.Context;
import android.util.Log;

import com.openingedu.mba.persist.DbOrder;
import com.openingedu.mba.service.OrderService;
import com.openingedu.mba.service.task.TaskCallback;
import com.openingedu.mba.service.task.TaskInvoker;

public class TaskCheckOrder extends TaskInvoker {

	private static final String TAG = TaskCheckOrder.class.getSimpleName();
	private final TaskCallback mCallback;
	private int mThreadId;
	private Context mContext;
	public TaskCheckOrder(TaskCallback callback, Context context) {
		super(callback);
		mCallback = callback;
		mContext = context;
	}

	
	
	@Override
	public void executeTask() {
		OrderService orderService = new OrderService();
		// TODO 每30s校验一次，校验6次，3分钟
		int checkNum = 0;
		while(checkNum < 6) {
			try {
				List<DbOrder> orderList = orderService.findWaitingPaidOrder(mContext);
				if (orderList == null || orderList.size() == 0) {
					break;
				}
				StringBuffer buf = new StringBuffer();
				for (DbOrder dbOrder : orderList) {
					Log.i(TAG, "check order status. orderID=" + dbOrder.getOrderID() + ", orderDID=" + dbOrder.getOrderDID());
					buf.append("," + dbOrder.getOrderDID());
				}
				boolean needBreak = orderService.checkOrderStatus(mContext, buf.toString());
				if (needBreak) {
					break;
				}
				checkNum++;
				// 休眠30s
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		getExecutionCallback().sendMessage(mThreadId);
	}

	@Override
	public void setThreadId(int threadId) {
		this.mThreadId = threadId;
	}

}
